package com.example.controller;


import com.example.bean.Merchant;
import com.example.bean.Result;
import com.example.service.MerchantService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 商户登录与注册
 */
@Slf4j
@RestController
public class MerchantController {
    @Autowired
    MerchantService MerchantService;

    //商户登录
    @PostMapping(value = "/api/merchantLogin")
    @CrossOrigin
    public Result login(@RequestParam("mName") String mName, @RequestParam("mPassword") String mPassword) {
        return MerchantService.login(mName, mPassword);
    }

    //商户注册
    @PostMapping(value = "/api/merchantRegister")
    @CrossOrigin
    public Result RegisterMerchant(@RequestBody Merchant mer) {
        Merchant merchant = MerchantService.SelectMerchant(mer.getMName());
        if (merchant != null) {
            //注册失败，用户已经存在，返回注册页面
            return new Result(401, "注册失败，用户已经注册", "");
        }
        //查询数据库中mid的最大值
        int maxMid = MerchantService.SelectMaxMid();
        //将最大值+1作为刚刚注册的商家的mid，存入数据库中
        int result = MerchantService.RegisterMerchant(maxMid+1,mer.getMName(), mer.getMPhone(), mer.getMPassword(), mer.getMEmail());
        if (result == 0) {
            //注册失败，跳转注册页面
            return new Result(400, "注册失败", "");
        }
        // 注册成功，跳转登录页面
        return new Result(200, "注册成功", "");
    }

    /**
     * 查询店铺名
     * @param mid 商家id
     * @return
     */
    @RequestMapping(value = "/api/findMerchantName")
    @CrossOrigin
    public Result findMerchantName(@RequestParam("mid")int mid){
        return MerchantService.findMerchantName(mid);
    }
}
